<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;

/**
 * 用户实名管理
 *
 * @icon fa fa-circle-o
 */
class Userauth extends Backend
{
    
    /**
     * UserCertification模型对象
     * @var \app\admin\model\UserCertification
     */
    protected $model = null;
    protected $searchFields = 'realname,id_number,bank_realname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('UserCertification');
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where('upload_time','>',0)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where('upload_time','>',0)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','user_id','realname','id_number','id_images','status','upload_time','audit_time']);
                //$row->visible(['user']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    //  判断状态是否改变，同步修改用户表状态
                    if ($params['status'] != $row->status)
                    {
                        \think\Config::load(APP_PATH.'api/config.php'); //  加载APi的配置
                        $user = \app\common\model\User::get($row->user_id);
                        if ($params['status'] == config('AuthStatus.Pass'))
                        {
                            //  审核通过    需要同步修改user表的数据
                            $user_data = ['is_certification' => config('IsCert.Certified')];
                        }
                        else
                        {
                            //  审核失败
                            $user_data = ['is_certification' => config('IsCert.UnCertified')];
                        }
                        if ($user) $user->save($user_data);
                        $params['audit_time'] = time();
                    }

                    //  修改这条记录的状态
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            \think\Config::load(APP_PATH.'api/config.php');
            foreach ($list as $k => $v) {
                if($v->status == config('AuthStatus.Pass'))
                {
                    $this->error('用户已认证通过，无法删除');
                }
                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}
